



#import "AreaTableview.h"

#import "MBNetTool.h"
#import "MBAPI.h"
#import "ArDistrictModel.h"
#import "ArRootModel.h"

#import "AreaCell.h"
#import "AreaFirstCell.h"

#define  Cell_hight MBScale(50)


@interface AreaTableview()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)NSMutableArray *AreaMut; // 区域、地铁



//三个tableview
@property(nonatomic,strong)UITableView *oneTableview;
@property(nonatomic,strong)UITableView *twoTableview;
@property(nonatomic,strong)UITableView *threeTableview;


//记录第一二三选中的indexpath
@property(nonatomic,strong)NSIndexPath *oneIndexPath;
@property(nonatomic,strong)NSIndexPath *twoIndexPath;
@property(nonatomic,strong)NSIndexPath *threeIndexPath;

@property(nonatomic,strong)UIButton *twoLatsButton;
@property(nonatomic,strong)UIButton *threeLastButton;


//记录请求参数防止请求错乱
@property(nonatomic,strong)NSMutableDictionary *lastDict;


@end
static NSString *AreaCell_Identi  = @"AreaCell";
static NSString *AreaFirstCell_Identi = @"AreaFirstCell";
@implementation AreaTableview

-(NSMutableArray *)AreaMut{
    if (!_AreaMut ) {
        _AreaMut = [NSMutableArray array];
        
        ArRootModel *model1 = [[ArRootModel alloc] init];
        model1.name = @"区域";
        
        ArRootModel *model2 = [[ArRootModel alloc] init];
        model2.name = @"地铁";
        
        [_AreaMut addObjectsFromArray:@[model1,model2]];
        
    }
    return  _AreaMut;
}
//-(NSMutableArray *)DistictMut{ //接口返回
//    if (!_DistictMut) {
//        _DistictMut = [NSMutableArray array];
//    }
//    return  _DistictMut;
//}

-(instancetype)initWithFrame:(CGRect)frame{
    if (self  = [super initWithFrame:frame]) {
        // 1、 生成三个tableview
        [self creatThreeTableview];
        
        //2、 网络获取district 数据
        [self Ar_DistrictDateGetedWithRootModel:self.AreaMut[0]];
        //3.默认选择
//        [self setSelectedCell]; ----改成默认选择tableHeaderView
        
    }
    return  self;
}
-(void)setSelectedCell{
    [_oneTableview selectRowAtIndexPath:_oneIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
   
    [_threeTableview selectRowAtIndexPath:_threeIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
    
    
}
-(void)creatThreeTableview{
    CGFloat tableWidth = self.bounds.size.width / 3;
    CGFloat tableHeight = 7 * ArCellHeight;
    
    for (int i = 0; i< 3; i++) {
        UITableView *tableview = [[UITableView alloc] initWithFrame:CGRectMake(tableWidth *i, 0, tableWidth, tableHeight) style:UITableViewStylePlain];
        tableview.tag = 200 + i;
        
        tableview.delegate = self;
        tableview.dataSource = self;
        tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        tableview.showsVerticalScrollIndicator = NO;
        
        if (i == 0) {
            [tableview registerNib:[UINib nibWithNibName:AreaFirstCell_Identi bundle:nil] forCellReuseIdentifier:AreaFirstCell_Identi];
        }else{
            [tableview registerNib:[UINib nibWithNibName:AreaCell_Identi bundle:nil] forCellReuseIdentifier:AreaCell_Identi];
        }
        
        
        [self addSubview:tableview];
        if (i == 0) {
            _oneTableview = tableview;
            
            _oneIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
          
            
        }else if (i == 1){
            _twoTableview = tableview;
            tableview.backgroundColor = MB_RGBA(242, 242, 242, 1.0);
            _twoIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
           // 添加头部的占位文字
            tableview.tableHeaderView = [self headerView_secondTableViewWithTag:1000];
           
        }else if (i == 2){
            _threeTableview = tableview;
            
            tableview.backgroundColor = MB_RGBA(242, 242, 242, 1.0);
             _threeIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
       
            tableview.tableHeaderView = [self headerView_secondTableViewWithTag:2000];
        }

    }
    
    
    
}

#pragma mark --添加顶部“不限” 二字
-(UIButton *)headerView_secondTableViewWithTag:(NSInteger)tag{
    
      CGFloat tableWidth = self.bounds.size.width / 3;
    UIButton *headerview = [UIButton buttonWithType:UIButtonTypeCustom];
    headerview.tag = tag;
    headerview.frame = CGRectMake(0, 0,tableWidth,Cell_hight);
    
    //添加分割线
    UIView *line1  =[[UIView alloc]initWithFrame:CGRectMake(0, Cell_hight- 1, tableWidth, 1)];
    line1.backgroundColor = MB_RGBA(221, 221, 221, 1.0);
    [headerview addSubview:line1];
    
    UIView *line2 =[[UIView alloc] initWithFrame:CGRectMake(tableWidth-1, 0, 1, Cell_hight)];
    line2.backgroundColor = MB_RGBA(221, 221, 221, 1.0);
    [headerview addSubview:line2];
    
    headerview.backgroundColor = MB_RGBA(242, 242, 242, 1.0);
    [headerview setTitle:@"不限" forState:UIControlStateNormal];
    [headerview setTitleColor:MB_mainSelectedColor forState:UIControlStateSelected];
    [headerview setTitleColor:MB_mainColor forState:UIControlStateNormal];
    [headerview addTarget:self action:@selector(clickHeaderView:) forControlEvents:UIControlEventTouchUpInside];
    if (tag == 1000) {
        _twoLatsButton =  headerview;
        
    }else if (tag == 2000){
        _threeLastButton = headerview;
    }
    headerview.selected = YES;
    
    return  headerview;
}
-(void)clickHeaderView:(UIButton *)button{
    
    button.selected = !button.selected;
    if (button.tag == 1000) {// 点击区县 “不限” 按钮
        
        [_twoTableview deselectRowAtIndexPath:_twoIndexPath animated:YES];
        [_threeTableview deselectRowAtIndexPath:_threeIndexPath animated:YES];
        _threeLastButton.selected = YES;
        if ([self.delegate respondsToSelector:@selector(AreaTableview:sendDistriceModel:regionModel:)]) {
            ArDistrictModel *districtModel = [[ArDistrictModel alloc] init];
            districtModel.name = @"";
            districtModel.code = @"";
            
            ArRegionModel *regionModel = [[ArRegionModel alloc] init];
            regionModel.name = @"";
            regionModel.code = @"";
            
            [self.delegate AreaTableview:self sendDistriceModel:districtModel regionModel:regionModel];
        }
        
        
    }else if(button.tag == 2000){ // 点击 区域“不限” 按钮
        
         [_threeTableview deselectRowAtIndexPath:_threeIndexPath animated:YES];
        
        ArDistrictModel *districtModel;
        if (_twoLatsButton.selected) {
            districtModel = [[ArDistrictModel alloc] init];
            districtModel.code = @"";
            districtModel.name = @"不限";
        }else{
            ArRootModel *rootModel = self.AreaMut[_oneIndexPath.row];
            districtModel = rootModel.rootMut[_twoIndexPath.row];
        }
        
    

        
        if ([self.delegate respondsToSelector:@selector(AreaTableview:sendDistriceModel:regionModel:)]) {
            
              [self.delegate AreaTableview:self sendDistriceModel:districtModel regionModel:nil];
            
        }
        
    }
    
    
}


#pragma mark -- 获取网络数据---区县
// 通过城市编号来获取区县编号
-(void)Ar_DistrictDateGetedWithRootModel:(ArRootModel *)rootModel{

    if (rootModel.rootMut.count) {
        [_twoTableview reloadData];
        
        return;
    }
    
    NSDictionary *dic = @{@"city":MBCityCode};
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:dic];
    [MBNetTool MBPost:Place_district paramater:dict success:^(id response) {
        
        if ([response[@"code"] integerValue] == 10000) {
            

            
            for (NSDictionary *dic_model in response[@"data"]) {
                ArDistrictModel *model = [[ArDistrictModel alloc] initWithDictionary:dic_model error:nil];
                
                [rootModel.rootMut addObject:model];
            }
            
  
        
         
            
            //网络数据回来之后，刷新第二列的tablview
            [_twoTableview reloadData];

//            [_twoTableview selectRowAtIndexPath:_twoIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
            //拿第二列的第一行去请求第三列tableview 的数据
            [self Ar_RegionDataGeted:rootModel.rootMut.firstObject];
            
        }
        
        
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark -- 获取网络数据---热门
//通过城市编号和区县编号 来获取热门区域
-(void)Ar_RegionDataGeted:(ArDistrictModel *)model{
    
    if (model.regionMut.count) {
        //数据请求回来之后，刷新第三列的tablview
        [_threeTableview reloadData];
        return;
    }
    
    NSDictionary *dic  = @{@"city":MBCityCode,
                           @"district":model.code
                           };
 
    
    NSMutableDictionary *mutDic = [NSMutableDictionary dictionaryWithDictionary:dic];
    _lastDict = mutDic;
    
    [MBNetTool MBPost:Place_region paramater:mutDic success:^(id response) {
//        if ([mutDic[@"district"] integerValue] != [_lastDict[@"district"] integerValue]) {
//            return ;
//        }
        
        if ([response[@"code"] integerValue] == 10000) {
            for (NSDictionary *dict in response[@"data"]) {
                ArRegionModel *regionModel  = [[ArRegionModel alloc] initWithDictionary:dict error:nil];
                [model.regionMut addObject:regionModel];
            }
        }
        
      //数据请求回来之后，刷新第三列的tablview
        [_threeTableview reloadData];
//        [_threeTableview selectRowAtIndexPath:_threeIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
        
    } failure:^(NSError *error) {
        
    }];
    
    
}

#pragma mark -- tableviewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView.tag == 200) {
        return  self.AreaMut.count;
    }else if (tableView.tag == 201){
    
        ArRootModel *rootModel =  self.AreaMut[_oneIndexPath.row];
        if (rootModel.rootMut.count) { //做为空判断
            return  rootModel.rootMut.count;
        }
        
    }else if (tableView.tag == 202){
        
        ArRootModel *rootModel = self.AreaMut[_oneIndexPath.row];
        
        if (rootModel.rootMut.count == 0) { return 0;}
        
        ArDistrictModel *ditrictModel = rootModel.rootMut[_twoIndexPath.row];
        if (ditrictModel.regionMut.count) {
            return  ditrictModel.regionMut.count;
        }
        
       
        
    }
    
    return  0;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return  1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BaseCell *cell;
    
    if (tableView.tag == 200) {
        
        cell = [tableView dequeueReusableCellWithIdentifier:AreaFirstCell_Identi];
        cell.rootModel = self.AreaMut[indexPath.row];
        
    }else if (tableView.tag == 201){
        
        ArRootModel *rootModel = self.AreaMut[_oneIndexPath.row];
        
        
        cell = [tableView dequeueReusableCellWithIdentifier:AreaCell_Identi];
        cell.districtModel = rootModel.rootMut[indexPath.row];
        
    }else if (tableView.tag == 202){
        
        ArRootModel *rootModel = self.AreaMut[_oneIndexPath.row];
        ArDistrictModel *model = rootModel.rootMut[_twoIndexPath.row];
        
        cell = [tableView dequeueReusableCellWithIdentifier:AreaCell_Identi];
        
        if (model.regionMut.count) {
             cell.regionModel =  model.regionMut[indexPath.row];
        }
       
        
    }
    
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    

   
    return  cell;
}



#pragma mark --tableviewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (tableView.tag == 200) {
        if (_oneIndexPath.row != indexPath.row) {
            _oneIndexPath = indexPath;
        }
        
        //进行网络请求
        
        if (indexPath.row == 0) {
            //通过城市编号 请求到---区县信息，然后通过区县信息请求到-- 热门
            [self Ar_DistrictDateGetedWithRootModel:self.AreaMut[0]];
            
            
        }else if (indexPath.row == 1){
            [_twoTableview reloadData];
            [_threeTableview reloadData];
        }
        
        
        
    }else if (tableView.tag == 201){
        
        if (_twoIndexPath.row != indexPath.row) {
//            [self tableView:tableView didDeselectRowAtIndexPath:_twoIndexPath];
            _twoIndexPath = indexPath;
        }
        
        _twoLatsButton.selected = NO;
        _threeLastButton.selected = YES;
        NSIndexPath *indexpath = [NSIndexPath indexPathForRow:0 inSection:0];
        [_threeTableview scrollToRowAtIndexPath:indexpath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
        
        ArRootModel *rootModel = self.AreaMut[_oneIndexPath.row];
        ArDistrictModel *districtModel =  rootModel.rootMut[indexPath.row];
        // 进行网络请求获取对应的第三列table 数据
       
        [self Ar_RegionDataGeted:districtModel];
        
    }else if (tableView.tag == 202){
        if (_threeIndexPath.row != indexPath.row) {
//            [self tableView:tableView didDeselectRowAtIndexPath:_threeIndexPath];
            _threeIndexPath = indexPath;
        }
        
        _threeLastButton.selected = NO;
        
        if ([self.delegate respondsToSelector:@selector(AreaTableview:sendDistriceModel:regionModel:)]) {
            ArRootModel *rootModel = self.AreaMut[_oneIndexPath.row];
            ArDistrictModel *ditrictModel = rootModel.rootMut[_twoIndexPath.row];
            ArRegionModel *regionModel = ditrictModel.regionMut[indexPath.row];
            
//            [self.delegate AreaTableview:self sendDistriceInfo:ditrictModel.name regionName:regionModel.name];
            
            [self.delegate AreaTableview:self sendDistriceModel:ditrictModel regionModel:regionModel];
        }
        
        
    }
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  Cell_hight;
}















@end
